package top.lishuoboy.redis.config;

import cn.hutool.core.bean.BeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

/**
 * @author lishuoboy
 * @date 2022/3/22 15:30
 */
@Slf4j
@Configuration
public class SpringRedisConfig {
    // RedisAutoConfiguration 配置的默认的 RedisTemplate
    /*
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }*/

    // 参考 RedisAutoConfiguration 配置的默认的 RedisTemplate，复制一份做自定义序列化器
    // 方式一：重新定义一个新的，覆盖spring自带的。注意：需要bean的名字与原注入的一样。为了防止覆盖以前的 RedisTemplate，bean的名字可以叫 jsonRedisTemplate
    @Bean
    RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        log.debug("template=={}", BeanUtil.beanToMap(template));
        /*
         * template=={
         *   exposeConnection=false,
         *   enableDefaultSerializer=true,
         *   defaultSerializer=null,
         *   keySerializer=null,
         *   valueSerializer=null,
         *   hashKeySerializer=null,
         *   hashValueSerializer=null,
         *   stringSerializer=org.springframework.data.redis.serializer.StringRedisSerializer@7bfa0f6e,
         *   connectionFactory=org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory@ac62681
         * }
         */

        // 自定义序列化器
        template.setKeySerializer(RedisSerializer.string());
        template.setValueSerializer(RedisSerializer.json());
        template.setHashKeySerializer(RedisSerializer.string());
        template.setHashValueSerializer(RedisSerializer.json());

        return template;
    }

    // 方式二：修改spring自带的。注意：引入后修改
//    @Bean
//    RedisTemplate<String, Object> myRedisTemplate(RedisTemplate redisTemplate) {
//        // 自定义序列化器
//        redisTemplate.setKeySerializer(RedisSerializer.string());
//        redisTemplate.setValueSerializer(RedisSerializer.json());
//        redisTemplate.setHashKeySerializer(RedisSerializer.string());
//        redisTemplate.setHashValueSerializer(RedisSerializer.json());
//
//        return redisTemplate;
//    }
}